package vpfarm.master;

import java.util.ArrayList;

import jtools.ai.agenten.AID;
import jtools.ai.agenten.AMessage;
import jtools.ai.agenten.Agent;
import jtools.ai.agenten.Behavior;
import jtools.ai.agenten.YelloPage;
import vpfarm.Constants;
import vpfarm.data.JobInfo;

public class BroadcastBehavior extends Behavior {

	private boolean done = false;
	private JobInfo jobInfo;
	
	public BroadcastBehavior(JobInfo jobInfo) {
		this.jobInfo = jobInfo;
	}

	public boolean done() {
		return done;
	}


	public void execute() {
		System.out.println("execute BroadCast");
		AMessage list = myAgent.reciveMessage(true);
		if (list.getSubject() != YelloPage.YELLOWPAGE_SEARCH){
			AMessage tmp = reciveMessage(false);
			if (tmp != null){
				if (tmp.getSubject() == YelloPage.YELLOWPAGE_SEARCH){
					pushBack(tmp);
					execute();
				}else
					pushBack(tmp);
			}
			myAgent.pushBack(list);
			return;
		}
		try{
			ArrayList<AID> aid = (ArrayList<AID>) list.getContent();
			System.out.println("Benachrichtige folgende Agenten:");
			if (aid != null){
				AMessage b = new AMessage(Constants.SEND_JOB_INFO);
				b.setContent(new JobInfo(this.jobInfo));
				for (int i = 0; i < aid.size(); i++){
					System.out.println(aid.get(i));
					b.addReciver(aid.get(i));
				}
				myAgent.sendMessage(b);
			}
			
			done = true;
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	public void onEnd() {
		System.out.println("Beende Broatcast");
	}

	@Override
	public void onStart() {
		AMessage askList = new AMessage(YelloPage.YELLOWPAGE_SEARCH);
		askList.setDescription(YelloPage.SEARCH_LIKE);
		askList.setContent(Constants.SLAVE_NAME);
		askList.addReciver(Agent.YELLOPAGE_NAME);
		myAgent.sendMessage(askList);
	}

}
